/**
 * @modal: 手动拆单
 */

import { useState, useEffect, useRef } from 'react';
import { Alert, message } from 'antd';
import { find, cloneDeep } from 'lodash';
import CommonLoading from '@/components/CommonLoading';
import CommonInputNumber from '@/pages/OrderModule/common/components/CommonInputNumber';
import Typography from '@/pages/OrderModule/common/components/Typography';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import { CommonTable } from '@/pages/OrderModule/common/components/CommonTable';
import { manualSplitOrderOp } from '../../../../services';
import Style from './index.module.less';

function SplitOrderModal({ selectKeys, orderList, handleOk, handleCancel }) {
 
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);

  const currentOrder = useRef({});

  useEffect(()=>{
    formatGoodsList();
  },[])

  // useEffect(()=>{
  //   console.log(data)
  // },[data])

  const formatGoodsList = () => {
    const order = find(orderList, ['id', selectKeys[0]]);
    if(order){
      currentOrder.current = order;
      setList(order.goodsList);
    }
  }

  function handleNumChange(e, index) {
    const val = parseInt(e.target.value);
    if (val == list[index].splitNum) {
      return;
    }
    const reg = /^[1-9]\d*$/;
    const arr = cloneDeep(list)
    if (reg.test(val)) {
      arr[index].splitNum = Math.min(arr[index].goodsNum, val);
    }else if(!val){
      arr[index].splitNum = undefined;
    }
    setList(arr)
  }

  const goodsColumns = [
    {
      title: '序号',
      dataIndex: 'field1',
      width:60,
      render(value, record, index) {
        return index + 1
      },
    },
    // {
    //   title: '图片',
    //   dataIndex: 'sysGoodsImage',
    //   render(value, record) {
    //     return <Image className={Style.goods_image} width={55} src={sysGoodsImage} />;
    //   },
    // },
    {
      title: '商品',
      dataIndex: 'sysGoodsName',
      render(value, record) {
        return <Typography as="s1">{value}</Typography>;
      },
    },
    {
      title: '商品编码',
      dataIndex: 'sysSkuCode',
      render(value, record) {
        return <Typography as="s1">{value}</Typography>;
      },
    },
    {
      title: '款式编码',
      dataIndex: 'sysSpuCode',
      render(value, record) {
        return <Typography as="s1">{value}</Typography>;
      },
    },
    {
      title: '当前数量',
      dataIndex: 'goodsNum',
      width:90,
      render(value, record) {
        // return <NumText as="s1" num={value} point={0} />;
        return value;
      },
    },
    {
      title: '拆出数量',
      dataIndex: 'splitNum',
      render(value, { goodsNum, id }, index) {
        return <CommonInputNumber 
        disabled={!selectedRowKeys.includes(id)}
        placeholder="请输数量" min={1} max={goodsNum-1} value={value} onBlur={e => handleNumChange(e, index)} />;
      },
    },
  ];

  async function handleSave() {
    if(!selectedRowKeys?.length){
      return message.info('请至少勾选1个拆出商品');
    }
    const filterGoods = [];
    selectedRowKeys.map(item=>{
      const obj = find(list, ['id', item]);
      obj && filterGoods.push({
        splitNum: obj.splitNum,
        orderGoodsId: obj.id,
        goodsNum: obj.goodsNum,//校验使用
      });
    })
    if(filterGoods?.length && filterGoods.every(item=>item.splitNum)){
      if(selectedRowKeys.length == list.length){//全部勾选
        const allSome = filterGoods.every(item=>item.splitNum == item.goodsNum);
        if(allSome){
         return message.info('拆出商品的订单不能与原订单完全相同，请重新勾选');
        }
      }
      setLoading(true);
      const { msg, data, success } = await manualSplitOrderOp({
        mainOrderId: currentOrder.current?.id,
        waitSplitOrderGoodsList: filterGoods
      })
      setLoading(false);
      if(success){
        message.success(msg);
        handleOk(3, data)
      }
    }else{
      return message.info('拆出数量不能为空');
    }
  }

  return (
    <CommonModal title={{ title: '手动拆单' }} open={true} width="870px" onOk={handleSave} onCancel={handleCancel}>
      <Alert showIcon message={<Typography as="s1">只有待审核订单允许拆单</Typography>} />
      <CommonTable
        className={Style.order_item_table}
        scroll={{ y: `calc(100vh - 250px)` }}
        columns={goodsColumns}
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedRowKeys) => {
            setSelectedRowKeys(selectedRowKeys);
          },
        }}
        rowKey='id'
        dataSource={list}
        pagination={false}
      />
      <CommonLoading loading={loading} />
    </CommonModal>
  );
}

export default SplitOrderModal;
